
import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/api/http_util.dart';
import 'package:loxen/mode/code.dart';
import 'package:loxen/mode/login_bean.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/save_util.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';
class CallBack{
  final void Function() onSuccess;
  final void Function(Exception error)  onError;

  const CallBack(this.onSuccess, this.onError);
}

class BindingPhoneViewModel extends BaseViewModel{
  CallBack _callBack;
  LoginBean _loginBean;
  String userError;
  String _platform;

  set callBack(CallBack value) {
    _callBack = value;
  }

  //未登录为true   登录为false
  bool isLogin() => _loginBean == null;

  LoginBean get loginBean => _loginBean;

  void initUser() async {
    String tonken = await SharedPreferencesUtil.getData(Constants.ACCESS_TOKEN);
    if (tonken != null && tonken != '') {
      _loginBean = LoginBean();
    }
  }

  void setPlatform(val) {
    _platform = val;
  }

  void register(String openid, String mobile, String code,
      {void Function() onSuccess, void Function(String error) onFail}) {
    ApiService.thirdPartRegister(_platform, openid, mobile, code)
        .flatMap((value) => compute(decodeLoginBean, value.data).asStream())
        .listen((event) {
      if (event.code == 2000) {
        _loginBean = event;
        SharedPreferencesUtil.putData(
            Constants.ACCESS_TOKEN, event.data.token);
        SharedPreferencesUtil.putData(
            Constants.REFRESH_TOKEN, event.data.rft);
        notifyListeners();
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onFail != null) onFail.call('登录失败');
      }
    }, onError: (error) {
      if (onFail != null) onFail.call('网络异常');
    });
  }

  void code(String mobile, String action,
      {void Function() onSuccess, void Function(String error) onFail}) {
    ApiService.code(mobile, action)
        .flatMap((value) => compute(decodeCode, value.data).asStream())
        .listen((event) {
      if (event.code == 2000) {
        if (onSuccess != null) onSuccess.call();
      } else {
        _callBack.onError(Exception('未知异常'));
        if (onFail != null) onFail.call('未知异常');
      }
    }, onError: (error) {
      if (onFail != null) {
        if (error is ServiceException) {
          var data = error.userMessage;
          if (data is Map) {
            onFail.call(data["mobile"].toString());
          }
        }
      }
    });
  }

  static LoginBean decodeLoginBean(dynamic json) {
    return LoginBean.fromJson(json);
  }

  static Roots decodeCode(dynamic json) {
    return Roots.fromJson(json);
  }
}
